import axios from 'axios'
import type { AxiosInstance } from 'axios'
import { LZRquestInterceptors, LZRequestConfig } from './type'
import { ElLoading } from 'element-plus'
import 'element-plus/theme-chalk/el-var.css'
import 'element-plus/theme-chalk/el-loading.css'
import type { LoadingInstance } from 'element-plus/lib/components/loading/src/loading'

class LZRquest {
  instance: AxiosInstance
  interceptors?: LZRquestInterceptors
  loading?: LoadingInstance
  showLoding: boolean

  constructor(config: LZRequestConfig) {
    this.instance = axios.create(config)
    this.showLoding = config.showLoading ?? false
    // 每个实例专属的拦截器
    this.interceptors = config.interceptors
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptors,
      this.interceptors?.requestInterceptorsCatch
    )
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptors,
      this.interceptors?.responseInterceptorsCatch
    )
    // 所有实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        // 是否开启加载动画
        if (this.showLoding) {
          this.loading = ElLoading.service({
            lock: true,
            text: '正在加载'
          })
        }
        return config
      },
      (err) => {
        return err
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        // 关闭加载动画
        this.loading?.close()
        return res.data
      },
      (err) => {
        this.loading?.close()
        return err
      }
    )
  }

  request<T = any>(config: LZRequestConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      // 单独对请求进行请求拦截
      if (config.interceptors?.requestInterceptors) {
        config = config.interceptors.requestInterceptors(config)
      }

      // 是否开启加载动画
      this.showLoding = config.showLoading ?? false

      this.instance
        .request<any, T>(config)
        .then((res) => {
          // 单独对请求进行响应拦截
          if (config.interceptors?.responseInterceptors) {
            res = config.interceptors.responseInterceptors(res)
          }
          resolve(res)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  get<T = any>(config: LZRequestConfig<T>): Promise<T> {
    return this.request({ ...config, method: 'GET' })
  }

  post<T = any>(config: LZRequestConfig<T>): Promise<T> {
    return this.request({ ...config, method: 'POST' })
  }

  delete<T = any>(config: LZRequestConfig<T>): Promise<T> {
    return this.request({ ...config, method: 'DELETE' })
  }

  patch<T = any>(config: LZRequestConfig<T>): Promise<T> {
    return this.request({ ...config, method: 'PATCH' })
  }
}

export default LZRquest
